/**
 * Created by 123 on 2017/3/23.
 */
import mqtt from 'mqtt';

export default {
  namespace: 'weather',

  state: {
    pm25: '-',
    pm10: '-',
    temperature: '-',
    quality: '-',
  },
  subscriptions: {

    connect({dispatch}){

      const client = mqtt.connect({host: 'mqtt.firy.cn', port: '15880'});
      client.on('connect', () => {
        client.subscribe('devices/whkj01/data')
      })
      client.on('message', (topic, message) => {
        const data = JSON.parse(String(message));

        const {pm25_cf, pm10_cf, temperature}=data.value;
        if (data.type == 'dust') {
          dispatch({type: 'getData', payload: {pm25: pm25_cf, pm10: pm10_cf}});
        } else if (data.type == 'air') {
          dispatch({type: 'getData', payload: {temperature: Math.round(temperature)}});
        }

      })
    },

  },
  reducers: {
    getData(state, {payload}){

      return {
        ...state, ...payload
      }
    },

  }
}
